<script lang="ts" setup>
// import type { DemoTableApi } from '../mock-api';

import type { VxeGridProps } from '#/adapter/vxe-table';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { ElButton, ElImage, ElTag, ElText } from 'element-plus';

import { useVbenForm } from '#/adapter/form';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import PictureUpload from '#/components/PictureUpload.vue';

// import { MOCK_API_DATA } from '../table-data';

import { Country_Region, Country_Region_obj } from '@vben/constants';
import { $t } from '@vben/locales';

import {
  CarAddApi,
  CarListApi,
  CarUpdateApi,
  fileUploadR2,
  getCompanySelectApi,
} from '#/api';

interface CarModal {
  /**
   * 车型基础信息
   */
  baseInfo: {
    /**
     * 地区
     */
    area: string;
    /**
     * 展示名
     */
    showName: string;
  }[];
  /**
   * 公司id集合
   */
  companyIdList: string[];
  /**
   * 图片OssObjectKeys
   */
  imgObjectKeys: string[];
  /**
   * 名称
   */
  innerName: string;
}

const id = ref('');
const gridOptions: VxeGridProps = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  columns: [
    { title: '序号', type: 'seq', width: 50 },
    { field: 'imageUrls', title: '图片', slots: { default: 'imageUrls' } },
    {
      field: 'companyInfo',
      title: '展示公司',
      slots: { default: 'companyInfo' },
    },
    { field: 'areaNames', title: '名称', slots: { default: 'areaNames' } },
    { field: 'baseInfo', title: '关联地区', slots: { default: 'baseInfo' } },
    {
      field: 'action',
      title: '操作',
      slots: { default: 'action' },
    },
  ],
  exportConfig: {},
  // height: 'auto', // 如果设置为 auto，则必须确保存在父节点且不允许存在相邻元素，否则会出现高度闪动问题
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        const res = await CarListApi({
          offset: page.currentPage,
          size: page.pageSize,
        });
        return {
          items: res.records,
          total: res.total,
        };
      },
    },
  },
  toolbarConfig: {
    custom: true,
    export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};
const areaList = ref([]);

const dataForm = ref({
  innerName: '',
  areaList: [],
});
const areaOptions = computed(() => {
  return Country_Region.map((item) => {
    return {
      label: $t(item.lan),
      value: item.value,
      areaNames:
        areaList.value.find((a) => a.value === item.value)?.areaNames || '',
    };
  });
});
const Com_Options = ref([]);
const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions,
});
const carSchema = computed(() => {
  const schema = [
    {
      // 组件需要在 #/adapter.ts内注册，并加上类型
      component: 'Input',
      fieldName: 'imgObjectKeys',
      label: '图片',
      modelPropName: 'imgObjectKeys',
      defaultValue: [],
      rules: 'required',
    },
    {
      // 组件需要在 #/adapter.ts内注册，并加上类型
      component: 'Input',
      fieldName: 'innerName',
      label: '名称',
      defaultValue: '',
      rules: 'required',
      componentProps: {
        placeholder: `该名称仅用于内部记录，不会展示至用户端`,
      },
    },
    {
      component: 'Select',
      // 字段名
      fieldName: 'companyIdList',
      // 界面显示的label
      label: '展示公司',
      defaultValue: [],
      componentProps: {
        placeholder: '请选择展示公司',
        // multiple: true,
        filterable: true,
        // remote: true,
        options: Com_Options,
        // remoteMethod: () => {
        //   getCompanySelectApi().then((res) => {
        //     Com_Options.value = res.data.map((item) => {
        //       return {
        //         label: item.companyName,
        //         value: item.id,
        //       };
        //     });
        //   });
        // },
      },
      rules: 'required',
    },
    {
      // 组件需要在 #/adapter.ts内注册，并加上类型
      component: 'Select',
      // 字段名
      fieldName: 'areaList',
      // 界面显示的label
      label: '展示地区',
      defaultValue: [],
      componentProps: {
        placeholder: '请选择展示地区',
        multiple: true,
        options: Country_Region.map((cr) => {
          return {
            label: $t(cr.lan),
            value: cr.value,
          };
        }),
      },
    },
  ];
  Country_Region.forEach((country) => {
    schema.push(
      {
        component: 'Input',
        fieldName: country.value,
        label: `${$t(country.lan)}车型名称`,
        defaultValue: '',
        componentProps: {
          placeholder: `请输入${$t(country.lan)}车型名称`,
        },
        dependencies: {
          if(values) {
            return values.areaList.includes(country.value);
          },
          triggerFields: ['areaList'],
        },
        rules: 'required',
      },
      {
        component: 'Input',
        fieldName: 'tips',
        dependencies: {
          if(values) {
            return values.areaList.includes(country.value);
          },
          triggerFields: ['areaList'],
        },
      },
    );
  });
  return schema;
});
const [BaseForm, formApi] = useVbenForm({
  showDefaultActions: false,
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  schema: carSchema.value,
});
const handleSubmitData = (data) => {
  const res = {
    baseInfo: [],
    innerName: data.innerName,
    imgObjectKeys: data.imgObjectKeys,
    companyIds: [data.companyIdList],
    companyIdList: [data.companyIdList],
  };
  data.areaList.forEach((area) => {
    res.baseInfo.push({
      showName: data[area],
      area,
    });
  });
  return res;
};
const handleDetailsData = (data) => {
  const res = { ...data };
  res.areaList = data.baseInfo.map((item) => {
    res[Country_Region_obj[item.area].value] = item.showName;
    return item.area;
  });
  res.imgObjectKeys = data.images;
  res.companyIdList = data.companyInfo[0].id;
  return res;
};
const isCarEdit = ref(false);
const [Modal, modalApi] = useVbenModal({
  onConfirm: () => {
    formApi
      .validate()
      .then((res) => {
        return res.valid ? Promise.resolve() : Promise.reject();
      })
      .then(() => {
        return formApi.getValues();
      })
      .then(async (res) => {
        modalApi.setState({ loading: true });
        const keys = await fileUploadR2(res.imgObjectKeys, {
          key: 'imageOssObjectKey',
          value: 'imageUrl',
        });
        return { ...res, imgObjectKeys: keys };
      })
      .then((res2) => {
        const subRes = handleSubmitData(res2);
        return isCarEdit.value
          ? CarUpdateApi({ ...subRes, id: id.value })
          : CarAddApi(subRes);
      })
      .then(() => {
        modalApi.setState({ loading: false });
        modalApi.close();
        gridApi.reload();
      })
      .catch(() => {
        modalApi.setState({ loading: false });
      });
  },
});
const openModal = () => {
  modalApi.open();
  modalApi.setState({ loading: true });
  getCompanySelectApi()
    .then((res) => {
      Com_Options.value = res.map((item) => {
        return {
          label: item.companyName,
          value: item.id,
        };
      });
      modalApi.setState({ loading: false });
    })
    .catch(() => {
      modalApi.setState({ loading: false });
    });
};
const addCar = () => {
  isCarEdit.value = false;
  openModal();
};
const editCar = (row) => {
  isCarEdit.value = true;
  id.value = row.id;
  formApi.setValues(handleDetailsData(row), false);
  openModal();
};
</script>

<template>
  <div class="vp-raw w-full">
    <Grid>
      <template #toolbar-tools>
        <ElButton class="mr-2" type="primary" @click="addCar">
          添加车型
        </ElButton>
      </template>
      <template #imageUrls="{ row }">
        <ElImage
          v-if="row.images.length > 0"
          :preview-src-list="row.images.map((item) => item.imageUrl)"
          :src="row.images[0].imageUrl"
          class="size-10"
          fit="contain"
        />
      </template>
      <template #companyInfo="{ row }">
        <div>
          <span v-for="com in row.companyInfo" :key="com.id">{{
            com.companyName
          }}</span>
        </div>
      </template>
      <template #areaNames="{ row }">
        <div>
          <ElTag v-for="tag in row.baseInfo" :key="tag.area">
            {{ tag.showName }}
          </ElTag>
        </div>
      </template>
      <template #baseInfo="{ row }">
        <div>
          <ElTag v-for="tag in row.baseInfo" :key="tag.area">
            {{ $t(Country_Region_obj[tag.area].lan) }}
          </ElTag>
        </div>
      </template>
      <template #action="{ row }">
        <ElButton type="text" @click="editCar(row)">编辑</ElButton>
      </template>
    </Grid>
    <Modal class="w-[600px]" title="添加车型">
      <BaseForm>
        <template #imgObjectKeys="data">
          <PictureUpload v-bind="data" />
        </template>
        <template #tips>
          <ElText class="mx-1" type="danger">
            该处信息会展示至用户端中的车型名称，请按照该地区所使用的语言填写。谨慎配置！
          </ElText>
        </template>
      </BaseForm>
    </Modal>
  </div>
</template>
